<template>
    <div>
        <div class="head">
            <div class="word box" style="width:25%">
                <h3>随机一词</h3>
                <h4 v-if="isShow">单词:{{ word.word }}</h4>
                <h5 v-if="isShow">意思:{{ word.translate }}</h5>
                <div class="button">
                    <el-button v-if="isShow" @click="randomaWord" type="success" round>下一词</el-button>
                </div>
                <h3 v-if="!isShow">加载中...</h3>
            </div>
            <div class="box" style="width:30%">
                <h3>请求信息</h3>
                <h4 v-if="apply == ''">暂无请求</h4>
                <div v-else>
                    <h4>请求类型：{{ apply.type }}</h4>
                    <h4>状态：{{ apply.hmid == null ? '未受理' : '已受理' }}</h4>
                    <el-popover placement="top" width="160" trigger="focus" style="margin-left:10px">
                        <p v-if="apply.hmid != null">宿管：{{ homemaster.name }}</p>
                        <p v-if="apply.hmid != null">电话：{{ homemaster.phone }}</p>
                        <p v-if="apply.hmid != null">邮箱：{{ homemaster.email }}</p>
                        <p>信息：{{ apply.infor }}</p>
                        <el-button slot="reference">详情</el-button>
                    </el-popover>
                    <el-button type="primary" plain v-if="apply.hmid != null" @click="open" slot="reference"
                        style="margin-left:10px">确认解决</el-button>
                    <el-button v-if="apply.hmid == null" type="primary" style="margin-left:10px" @click="updataApply"
                        plain>修改</el-button>
                    <el-button v-if="apply.hmid == null" type="danger" style="margin-left:10px" @click="cancelApply"
                        plain>撤销</el-button>
                </div>
            </div>
            <el-calendar class="box" v-model="value">
            </el-calendar>
        </div>
        <div class="foot">
            <div class="box subfa" style="width:41%;">
                <h3>个人信息</h3>
                <h4>姓名：{{ student.name }}</h4>
                <h4>性别：{{ student.sex }}</h4>
                <h4>专业：{{ student.dept }}</h4>
                <span class="dor">
                    <h4 :class="student.ishome ? 'green' : 'red'">状态:<i style="font-style: normal;">{{ student.ishome ?
                        '在寝' : '不在寝' }}</i></h4>
                    <h4 v-show="isLate" class="red">时间不早了，请尽快回寝</h4>
                    <el-switch v-model="student.ishome" active-color="#13ce66" inactive-color="#ff4949" active-text="到寝"
                        inactive-text="不在寝" disabled>
                    </el-switch>
                </span>
                <h4>电话：{{ student.phone }}</h4>
                <h4>邮箱：{{ student.email }}</h4>
            </div>
            <div class="box" style="width:50%;">
                <h3>宿舍相关信息</h3>
                <h3 v-show="!isShowDormitory">加载中...</h3>
                <h4 v-show="isShowDormitory">我的寝室：{{ building }}栋{{ room }}室</h4>
                <span class="bill">
                    <h4 :class="isShowBL ? 'red' : ''" v-show="isShowDormitory">当前照明电费：{{ dormitory.billlight }}</h4>
                    <h4 style="margin-left:15px" class="red" v-if="isShowBL">当前已欠费，请缴费</h4>
                </span>
                <span class="bill">
                    <h4 :class="isShowBA ? 'red' : ''" v-show="isShowDormitory">当前空调电费：{{ dormitory.billaircon }}</h4>
                    <h4 style="margin-left:15px" class="red" v-if="isShowBA">当前已欠费，请缴费</h4>
                </span>
                <div style="text-align: center;">
                    <el-button type="primary" @click="dialogFormVisible = true">缴费</el-button>
                </div>
            </div>
        </div>
        <el-dialog title="充值电费" :visible.sync="dialogFormVisible">
            <el-form :model="moneyForm" :rules="rules">
                <el-form-item label="选择充值项目：" :label-width="formLabelWidth">
                    <el-select v-model="moneyForm.type" placeholder="请选择活动区域">
                        <el-option label="照明" :value="1"></el-option>
                        <el-option label="空调" :value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="输入要充值的金额：" :label-width="formLabelWidth" prop="money">
                    <el-input v-model="moneyForm.money" style="width:70%" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label='输入"确认充值"以确认' :label-width="formLabelWidth">
                    <el-input v-model="sure" style="width:70%" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="submit">确 定</el-button>
            </div>
        </el-dialog>
        <div id="container"></div>
    </div>
</template>
<script>
import AMapLoader from '@amap/amap-jsapi-loader';
export default {
    name: 'HomeS',
    data() {
        return {
            value: new Date(),
            words: [],
            word: {},
            dormitory: {},
            student: {},
            apply: {},
            homemaster: {},
            moneyForm: {
                type: 1,
                money: 0,
            },
            map: null,
            sure: '',
            building: '',
            room: '',
            isLate: false,
            isShow: false,
            isShowDormitory: false,
            isShowBL: false,
            isShowBA: false,
            dialogFormVisible: false,
            formLabelWidth: '160px',
            lng: 0,
            lat: 0,
            postitionStatus: '',
            rules: {
                money: [
                    { required: true, message: '请输入金额', trigger: 'blur' }
                ],
            }
        }
    },
    methods: {
        open() {
            let _this = this
            this.$confirm('确定已解决吗', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                _this.solved()
            }).catch(() => {

            })
        },
        updataApply() {
            this.$router.replace({ path: '/editapply' })
        },
        getWords() {
            let _this = this
            axios.get('http://localhost:8081/word/getWords').then(function (resp) {
                _this.words = resp.data
                _this.randomaWord()
            })
        },
        randomaWord() {
            let id = Math.floor(Math.random() * this.words.length) + 1
            this.word = this.words[id]
            this.isShow = true
        },
        change() {
            let time = new Date
            this.isLate = false
            if (!this.student.ishome) {
                if (time.getHours() > 22)
                    this.isLate = true
                else if (time.getHours() == 22)
                    if (time.getMinutes() > 30)
                        this.isLate = true
                    else if (time.getMinutes() == 30)
                        if (time.getSeconds() > 0)
                            this.isLate = true
                        else if (time.getSeconds() == 0)
                            if (time.getMilliseconds() > 0)
                                this.isLate = true
                if (time.getHours() < 4)
                    this.isLate = true
            }
        },
        async changeIsHome() {
            await this.getPostition()
            console.log(this.lng+","+this.lat);
            let left = 116.474459
            let right = 116.47792
            let up = 31.761536
            let bottom = 31.760183
            if (this.postitionStatus) {
                alert("网络出错啦！")
            } else if (this.lng > left && this.lng < right && this.lat > bottom && this.lat < up) {
                if (!this.student.ishome) {
                    this.student.ishome = true
                    axios.get(`http://localhost:8081/student/changeIsHomeById/${true}/${this.student.sid}`).catch(function () {
                        alert("网络出错啦！")
                    })
                }
            } else {
                if (this.student.ishome) {
                    this.student.ishome = false
                    axios.get(`http://localhost:8081/student/changeIsHomeById/${false}/${this.student.sid}`).catch(function () {
                        alert("网络出错啦！")
                    })
                }
            }
            this.change()
        },
        loadDormitory() {
            let _this = this
            axios(`http://localhost:8081/dormitory/getDormitoryById/${_this.building}/${_this.room}`).then(function (resp) {
                _this.dormitory = resp.data
                _this.isShowDormitory = true
                if (_this.dormitory.billlight < 0)
                    _this.isShowBL = true
                else
                    _this.isShowBL = false
                if (_this.dormitory.billaircon < 0)
                    _this.isShowBA = true
                else
                    _this.isShowBA = false
            })
        },
        submit() {
            let _this = this
            if (this.sure != '确认充值') {
                alert('请正确书写"确认充值"')
                return
            }
            if (parseFloat(this.moneyForm.money) < 0 || isNaN(parseFloat(this.moneyForm.money))) {
                alert('充值金额有误')
                return
            }
            axios.get(`http://localhost:8081/dormitory/rechargeBills/${this.building}/${this.room}`, { params: this.moneyForm }).then(function (resp) {
                alert('充值成功')
                _this.moneyForm.money = ''
                _this.moneyForm.type = 1
                _this.sure = ''
                _this.dialogFormVisible = false
                _this.loadDormitory()
            }).catch(function () {
                alert('充值失败，请稍后')
                _this.moneyForm.money = ''
                _this.moneyForm.type = 1
                _this.sure = ''
            })
        },
        loadHomemaster() {
            let _this = this
            axios.get(`http://localhost:8081/homemaster/getHMById/${_this.apply.hmid}`).then(function (resp) {
                _this.homemaster = resp.data
            })
        },
        loadApplyBySid() {
            let _this = this
            axios.get(`http://localhost:8081/apply/getApplyBySid/${this.student.sid}`).then(function (resp) {
                _this.apply = resp.data
                if (_this.apply.hmid != '') {
                    _this.loadHomemaster()
                }
            })
        },
        solved() {
            let _this = this
            axios.get(`http://localhost:8081/apply/solvedById/${this.apply.id}`).then(function () {
                axios.get(`http://localhost:8081/apply/getApplyBySid/${_this.student.sid}`).then(function (resp) {
                    console.log(resp.data);
                    _this.apply = resp.data
                })
            }).catch(function () {
                alert('网络延迟，请稍后')
            })
        },
        getPostition() {
            const _this = this
            this.postitionStatus = 1
            return new Promise(async (resolve, reject) => {
                window._AMapSecurityConfig = {
                    securityJsCode: "644be40ba32c46c47701e0df80868006",
                };
                AMapLoader.load({
                    key: "ff0df2664ba99ffa7489a95f3b5fd179", // 申请好的Web端开发者Key，首次调用 load 时必填
                    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                    plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
                }).then((AMap) => {
                    _this.map = new AMap.Map("container", {
                        // 设置地图容器id
                        zoom: 10, // 初始化地图级别
                    });
                    AMap.plugin('AMap.Geolocation', function () {
                        var geolocation = new AMap.Geolocation({
                            enableHighAccuracy: true, // 是否使用高精度定位，默认：true
                            timeout: 10000, // 设置定位超时时间，默认：无穷大
                            offset: [10, 20],  // 定位按钮的停靠位置的偏移量
                            zoomToAccuracy: true,  //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                            position: 'RB' //  定位按钮的排放位置,  RB表示右下
                        })
                        geolocation.getCurrentPosition(function (status, result) {
                            if (status == 'complete') {
                                _this.lng = result.position.lng
                                _this.lat = result.position.lat
                                _this.postitionStatus = 0
                                console.log(result);
                                resolve(result)
                            } else {
                                console.log(result);
                                reject(result)
                            }
                        });
                    })
                }).catch((e) => {
                    console.log(e);
                    reject(e)
                });
            })
            },
                getStudentById() {
                return new Promise((resolve, reject) => {
                    axios(`http://localhost:8081/student/getStudentById/${JSON.parse(localStorage.getItem('student')).sid}`).then(res => {
                        resolve(res.data);
                    }).catch(err => {
                        reject(err);
                    })
                })
            },
                cancelApply() {
                let _this = this
            this.$confirm('确定撤销吗', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    _this.solved()
                }).catch(() => {

                })
            }
    },
        async mounted() {
            let _this = this
            this.student = await this.getStudentById();
            this.building = this.student.dorid.split('#')[0]
            this.room = this.student.dorid.split('#')[1]
            this.loadDormitory()
            this.getWords()
            this.loadApplyBySid()
            this.changeIsHome()
        },
    }
</script>

<style scoped>
.el-calendar {
    font-size: 14px;
    width: 30%;
}

::v-deep .next {
    border: none;
}

::v-deep td {
    border: none;
}

::v-deep .el-calendar-day {
    height: 30px;
    text-align: center;
    border: none;
}

.box {
    margin-top: 10px;
    background-color: #fff;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 3px 3px 6px 2px rgba(0, 0, 0, 0.5);
}

.head {
    display: flex;
    justify-content: space-between;
}

.word {
    position: relative;
}

.button {
    position: absolute;
    text-align: center;
    bottom: 10%;
    right: 10%;
}

.dor {
    display: flex;
    justify-content: space-between;
}

.dor h4 {
    margin: 0;
}

.red {
    color: red;
}

.green {
    color: green;
}

.subfa {
    position: relative;
}

.submit {
    position: absolute;
    right: 10%;
    bottom: 10%;
}

.foot {
    display: flex;
    justify-content: space-between;
}

.bill {
    display: flex;
}

.bill h4 {
    margin-top: 0;
}
</style>